package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class H1wMetaObjectHandler implements MetaObjectHandler {
        @Override
        public void insertFill(MetaObject metaObject) {
            try {
                Date time = DateUtils.getNowDate();
                if (metaObject.hasSetter("createTime")) {
                    log.debug("自动插入 createTime");
                    this.setFieldValByName("createTime", time, metaObject);
                }
                if (metaObject.hasSetter("updateTime")) {
                    log.debug("自动插入 updateTime");
                    this.setFieldValByName("updateTime", time, metaObject);
                }
                if (metaObject.hasSetter("createBy")) {
                    log.debug("自动插入 createBy");
                    this.setFieldValByName("createBy", SecurityUtils.getUsername(), metaObject);
                }
                if (metaObject.hasSetter("updateBy")) {
                    log.debug("自动插入 updateBy");
                    this.setFieldValByName("updateBy", SecurityUtils.getUsername(), metaObject);
                }
            } catch (Exception e) {
                log.error("自动注入失败:{}", e);
            }
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            try {
                Date time = DateUtils.getNowDate();
                if (metaObject.hasSetter("updateTime")) {
                    log.debug("自动插入 updateTime");
                    this.setFieldValByName("updateTime", time, metaObject);
                }
                if (metaObject.hasSetter("updateBy")) {
                    log.debug("自动插入 updateBy");
                    this.setFieldValByName("updateBy", SecurityUtils.getUsername(), metaObject);
                }
            } catch (Exception e) {
                log.error("自动注入失败:{}", e);
            }
        }
}
